import { BUNDLE_TYPE_ENUM } from "../../base/EnumIndex";
import { LEVEL_COL_NUM, LEVEL_NUM_IN_PAGE } from "../../base/GameIndex";
import LevelItem from "../../item/LevelItem";
import { ResManager } from "../../manager/ResManager";
import { LvInfo } from "../../model/OtherModel";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PageNode extends cc.Component {
    idx: number = 0;
    itemList: cc.Node[] = [];


    item: cc.Prefab;
    itemNodeList: cc.Node[] = [];
    onLoad() {
        this.itemNodeList = [];
    }
    async init(idx: number, dataList: LvInfo[]) {
        this.item = await ResManager.ins.loadRes('prefab/node/lvItem', cc.Prefab, BUNDLE_TYPE_ENUM.HOME)
        this.updateView(idx, dataList);
    }
    updateView(idx: number, dataList: LvInfo[]) {
        this.idx = idx;
        this.itemList.length = 0;
        let height = 0;
        for (let i = 0; i < LEVEL_NUM_IN_PAGE; i++) {
            let item = this.getItem(i);
            item.parent = this.node;
            item.setPosition(0, 0);
            height = item.height;

            let levelItem = item.getComponent(LevelItem);
            levelItem.initLevelItem(dataList[i]);
            item.active = dataList[i] || dataList[i] === null ? true : false;
        }
        let row = Math.ceil(dataList.length / LEVEL_COL_NUM);
        let leftRow = (LEVEL_NUM_IN_PAGE / LEVEL_COL_NUM) - row;
        if (leftRow > 0) {
            let offsetY = leftRow * height / 2 + (leftRow - 1) * this.node.getComponent(cc.Layout).spacingY / 2;
            this.node.y += offsetY;
        } else {
            this.node.y = 0;
        }
    }
    updateLockState() {
        for (let i = 0; i < this.itemNodeList.length; i++) {
            let item = this.itemNodeList[i];
            let levelItem = item.getComponent(LevelItem);
            levelItem.updateLockState();
        }
    }
    updateItemLockState() {
        for (let i = 0; i < this.itemNodeList.length; i++) {
            let item = this.itemNodeList[i];
            let levelItem = item.getComponent(LevelItem);
            if (levelItem.isCurrentLv()) {
                levelItem.updateLockState();
                break;
            }
        }
    }

    getItem(idx: number) {
        let node = this.itemNodeList[idx];
        if (!node) {
            node = cc.instantiate(this.item);
            this.itemNodeList[idx] = node;
        }
        return node;
    }
}
